Product
Socket Now Supports uv.lock Files
Socket now supports uv.lock files to ensure consistent, secure dependency resolution for Python projects and enhance supply chain security.
@placekit/autocomplete-js
Advanced tools
All-in-one address autocomplete experience for your web apps
Quick start • Features • Reference • Customize • Additional notes • License
PlaceKit Autocomplete JavaScript Library is a standalone address autocomplete field for your application, built on top of our PlaceKit JS client. Under the hood it relies on Popper to position the suggestions list, and on Flagpedia to display flags on country results.
If you already use a components library with an autocomplete field, or need a more advanced usage, please refer to our PlaceKit JS client reference and its examples.
For React implementations, check our PlaceKit Autocomplete React library. And for Vue implementations, check our Vue.js example.
First, import the library and the default stylesheet into the <head>
tag in your HTML:
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@placekit/autocomplete-js@1.6.0/dist/placekit-autocomplete.min.css" />
<script src="https://cdn.jsdelivr.net/npm/@placekit/autocomplete-js@1.6.0"></script>
After importing the library, placekitAutocomplete
becomes available as a global:
<input type="search" placeholder="Search place..." class="pka-input" id="placekit" />
<script>
const pka = placekitAutocomplete('<your-api-key>', {
target: '#placekit',
countries: ['fr'],
// other options...
});
</script>
Or if you are using native ES Modules:
<script type="module">
import placekit from 'https://cdn.jsdelivr.net/npm/@placekit/autocomplete-js@1.6.0/dist/placekit-autocomplete.esm.js';
const pka = placekitAutocomplete(/* ... */);
// ...
</script>
NOTE: Make sure to call placekitAutocomplete
after the DOM is loaded so the input can be found.
First, install PlaceKit Autocomplete using npm package manager:
npm install --save @placekit/autocomplete-js
Then import the package and perform your first address search:
// CommonJS syntax:
const placekitAutocomplete = require('@placekit/autocomplete-js');
// ES6 Modules syntax:
import placekit from '@placekit/autocomplete-js';
const pka = placekitAutocomplete('<your-api-key>', {
target: '#placekit',
countries: ['fr'],
// other options...
});
Don't forget to import @placekit/autocomplete-js/dist/placekit-autocomplete.css
if you want to use our default style.
If you have trouble importing CSS from node_modules
, copy/paste its content into your own CSS.
👉 Check out our examples for different use cases!
placekitAutocomplete()
pka.input
pka.options
pka.configure()
pka.state
pka.on()
pka.handlers
pka.requestGeolocation()
pka.clearGeolocation()
pka.open()
pka.close()
pka.clear()
pka.setValue()
pka.destroy()
placekitAutocomplete()
PlaceKit Autocomplete initialization function returns a PlaceKit Autocomplete client, named pka
in all examples.
const pka = placekitAutocomplete('<your-api-key>', {
target: '#placekit',
countries: ['fr'],
maxResults: 10,
});
Parameter | Type | Description |
---|---|---|
apiKey | string | API key |
options | key-value mapping (optional) | Global parameters (see options) |
⚠️ target
must be set when instanciating placekitAutocomplete
, all other options can be set later with pka.configure()
.
pka.input
Input field element passed as target
option, read-only.
console.log(pka.input); // <input ... />
pka.options
Options from both PlaceKit Autocomplete and PlaceKit JS client, read-only.
console.log(pka.options); // { "target": <input ... />, "language": "en", "maxResults": 10, ... }
Option | From | Type | Default | Description |
---|---|---|---|---|
target | AutoComplete | string|Element | - | Target input element or (unique) selector. |
offset | AutoComplete | integer | 4 | Gap between input and suggestions list in pixels. |
template | AutoComplete | (item: object) => string | see index.js | Suggestion item formatting function. |
formatValue | AutoComplete | (item: object) => string | see index.js | Input value formatting function when selected from list. |
noResults | AutoComplete | string|(query: string) => string | see index.js | No result template. |
strategy | AutoComplete | 'absolute' | 'fixed' | absolute | Popper positioning strategy |
flip | AutoComplete | boolean | false | Flip position top when overflowing. |
countryAutoFill | Autocomplete | boolean? | false | Autofill current country by IP when types: ['country'] . |
className | AutoComplete | string | undefined | Additional suggestions panel CSS class(es). |
maxResults | JS client | integer | 5 | Number of results per page. |
language | JS client | string? | undefined | Preferred language for the results(1), two-letter ISO language code. Supported languages are en and fr . By default the results are displayed in their country's language. |
types | JS client | string[]? | undefined | Type of results to show. Array of accepted values: street , city , country , airport , bus , train , townhall , tourism . Prepend - to omit a type like ['-bus'] . Unset to return all. |
countries | JS client | string[]? | undefined | Countries to search in, or fallback to if countryByIP is true . Array of two-letter ISO country codes(1). |
countryByIP | JS client | boolean? | undefined | Use IP to find user's country (turned off). |
coordinates | JS client | string? | undefined | Coordinates to search around. Automatically set when calling pka.requestGeolocation() . |
[1]: See Scope and Limitations for more details.
countries
option is requiredThe countries
option is required at search time, but we like to keep it optional across all methods so developers remain free on when and how to define it:
placekit()
,pk.configure()
,pk.search()
.If countries
is missing or invalid, you'll get a 422
error, excepted whentypes
option is set to ['country']
only.
countryByIP
optionSet countryByIP
to true
when you don't know which country users will search addresses in. In that case, the option countries
will be used as a fallback if the user's country is not supported:
pka.configure({
countryByIP: true, // use user's country, based on their IP
countries: ['fr', 'be'], // returning results from France and Belgium if user's country is not supported
});
countryAutoFill
optionWhen making a country-only autocomplete field, this option enhances the experience by automatically filling the input detected with the user's IP.
It works only when types
option is set only with the conutry
value:
const pka = placekitAutocomplete('<your-api-key>', {
target: '#placekit',
types: ['country'],
countryAutoFill: true,
});
⚠️ It makes an automatic call to the PlaceKit API and therefore counts as billable usage.
See our country field example.
pka.configure()
Updates all parameters (except target
). Returns the instance so you can chain methods.
pka.configure({
className: 'my-suggestions',
flip: true,
formatValue: (item) => `${item.name} ${item.city}`,
language: 'fr',
maxResults: 5,
});
Parameter | Type | Description |
---|---|---|
opts | key-value mapping (optional) | Global parameters (see options) |
pka.state
Read-only object of input state.
console.log(pka.state); // {dirty: false, empty: false, freeForm: true, geolocation: false}
// `true` after the user modifies the input value.
console.log(pka.state.dirty); // true or false
// `true` whenever the input value is not empty.
console.log(pka.state.empty); // true or false
// `true` if the input has a free form value or `false` if value is selected from the suggestions.
console.log(pka.state.freeForm); // true or false
// `true` if device geolocation has been granted.
console.log(pka.state.geolocation); // true or false
The freeForm
value comes handy if you need to implement a strict validation of the address, but we don't interfere with how to implement it as input validation is always very specific to the project's stack.
pka.on()
Register event handlers, methods can be chained.
pka.on('open', () => {})
.on('close', () => {})
.on('results', (query, results) => {})
.on('pick', (value, item, index) => {})
.on('error', (error) => {})
.on('dirty', (bool) => {})
.on('empty', (bool) => {})
.on('freeForm', (bool) => {})
.on('geolocation', (bool, position) => {});
.on('state', (state) => {})
If you register a same event twice, the first one will be replaced.
So, to remove an handler, simply assign undefined
:
pka.on('open'); // clears handler for 'open' event
open
Triggered when panel opens.
close
Triggered when panel closes.
results
Triggered when suggestions list gets updated, same as when the user types or enables geolocation.
Parameter | Type | Description |
---|---|---|
query | string | Input value. |
results | object[] | Results returned from API. |
pick
Triggered when user selects an item from the suggestion list by clicking on it or pressing ENTER after using the keyboard navigation.
Parameter | Type | Description |
---|---|---|
value | string | Input value (value returned by options.formatValue() ). |
item | object | All item details returned from API. |
index | number | Position of the selected item in the suggestions list, zero-based. |
error
Triggered on server error.
Parameter | Type | Description |
---|---|---|
error | object | Error details. |
dirty
Triggered when the input value changes.
Parameter | Type | Description |
---|---|---|
dirty | boolean | true after the user modifies the value. |
empty
Triggered when input value changes.
Parameter | Type | Description |
---|---|---|
empty | boolean | true if input is empty. |
freeForm
Triggered when input value changes.
Parameter | Type | Description |
---|---|---|
freeForm | boolean | true on user input, false on pick event. |
geolocation
Triggered when state.geolocation
value changes (a.k.a. when pka.requestGeolocation
is called).
Parameter | Type | Description |
---|---|---|
geolocation | boolean | true if granted, false if denied. |
position | GeolocationPosition | undefined | Passed when geolocation is true . |
state
Triggered when one of the input states changes.
Parameter | Type | Description |
---|---|---|
state | object | The current input state. |
pka.handlers
Reads registered event handlers, read-only.
pka.on('open', () => {});
console.log(pka.handlers); // { open: ... }
pka.requestGeolocation()
Requests device's geolocation (browser-only). Returns a Promise with a GeolocationPosition
object.
pka.requestGeolocation({ timeout: 10000 }).then((pos) => console.log(pos.coords));
Parameter | Type | Description |
---|---|---|
opts | key-value mapping (optional) | navigator.geolocation.getCurrentPosition options |
cancelUpdate | boolean (optional) | If false (default), suggestions list updates immediately based on device location. |
The location will be store in the coordinates
global options, you can still manually override it.
state.geolocation
will be set to true
, dispatching both the geolocation
and state
events.
pka.clearGeolocation()
Clear device's geolocation stored with pka.requestGeolocation
.
pka.clearGeolocation();
The global option coordinates
will be deleted and the state.geolocation
will be set to false
, dispatching both the geolocation
and state
events.
pka.open()
Opens the suggestion panel.
pka.open();
pka.close()
Closes the suggestion panel.
pka.close();
pka.clear()
Clears the input value, focus the field, and closes the suggestion panel.
pka.clear();
pka.setValue()
Manually set the input value. Useful for third-party wrappers like React.
Parameter | Type | Description |
---|---|---|
value | `string | null` (optional) |
notify | boolean (optional) | Pass true to dispatch change and input events and update state (default false ). |
pka.setValue('new value');
pka.setValue('new value', true); // dispatch `change` and `input` event
NOTE: state.empty
will automatically be updated based on the input value if notify: true
. state.dirty
and state.freeForm
remain unchanged until the user focuses the input.
pka.destroy()
Removes the suggestions panel from the DOM and clears all event handlers from window
and input
that were added by PlaceKit Autocomplete.
pka.destroy();
You have full control over the input element as PlaceKit Autocomplete doesn't style nor alter it by default.
We still provide a style that you can apply by adding the .pka-input
class to your input element.
Colors, border-radius, font and overall scale (in rem
) are accessible over variables:
:root {
--pka-scale: 1rem;
--pka-color-accent: 1, 73, 200;
--pka-color-black: 29, 41, 57;
--pka-color-darker: 52, 64, 84;
--pka-color-dark: 152, 162, 179;
--pka-color-light: 207, 213, 221;
--pka-color-lighter: 243, 244, 246;
--pka-color-white: 255, 255, 255;
--pka-border-radius: 6px;
--pka-font-family: system-ui, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
--pka-z-index: 9999;
}
/* dark mode overrides */
body.dark,
body[data-theme="dark"] {
--pka-color-accent: 55, 131, 249;
}
For advanced customization, refer to our stylesheet to learn about the available classes if you need to either override some or start a theme from scratch.
A dark mode is available whenever you add .dark
class or data-theme="dark"
attribute to the <body>
element.
⚠️ NOTE: you are not allowed to hide the PlaceKit logo unless we've delivered a special authorization. To request one, please contact us using our contact form.
value
attribute on the <input>
will automatically trigger a first search request when the user focuses the input.PlaceKit Autocomplete JS Library is an open-sourced software licensed under the MIT license.
FAQs
PlaceKit Autocomplete JavaScript library
We found that @placekit/autocomplete-js demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Socket now supports uv.lock files to ensure consistent, secure dependency resolution for Python projects and enhance supply chain security.
Research
Security News
Socket researchers have discovered multiple malicious npm packages targeting Solana private keys, abusing Gmail to exfiltrate the data and drain Solana wallets.
Security News
PEP 770 proposes adding SBOM support to Python packages to improve transparency and catch hidden non-Python dependencies that security tools often miss.